import { MtEntity } from '@/api/manager/mt'
import { Cascade, IMcc, MccCurrentMt, MccModel, Meeting } from '../interface'

export function isCascadeTree(tree: MccModel<Meeting>) {
	if (tree.mtKey === '0.0.0.0_0') {
		let onlineMeeting = tree.children.filter((x) => !x.mcc.isMt && x.mcc.status.isOnline)
		if (onlineMeeting.length === 0) {
			return false
		}
	}
	return true
}

export function flatGetAllMeetingList(tree: MccModel<Meeting>): Cascade[] {
	let stack: MccModel<IMcc>[] = [tree]
	let result = []
	while (stack.length !== 0) {
		const item = stack.shift()!
		if (!item.mcc.isMt && item.mcc.status.isOnline && item.mcc.confLevel !== 1) {
			result.push({
				id: item.mcc.smcuMtid,
				name: item.mcc.name,
				confLevel: item.mcc.confLevel,
			})
		}
		if (item.children && item.children.length > 0) {
			for (let i = item.children.length - 1; i >= 0; i--) {
				stack.unshift(item.children[i])
			}
		}
	}
	return result
}

export function cascadeNodesTranslator(list: MtEntity[]): MccCurrentMt[] {
	return list.map((mcc) => {
		if (mcc.mt_type === 7) {
			return { account: mcc.e164, accountType: 10, moid: '', e164: mcc.e164 }
		} else {
			return { account: mcc.account, accountType: mcc.account_type, moid: mcc.moid, e164: mcc.e164 }
		}
	})
}

export function getCurrentMeetingMts(tree: MccModel<Meeting>) {
	let stack: MccModel<IMcc>[] = [tree]
	let result: MccModel<IMcc>[] = []
	while (stack.length > 0) {
		const item = stack.shift()!
		if (!item.mcc.isMt && item.mcc.confLevel === 2) {
			result = item.children
			break
		}
		if (item.children && item.children.length > 0) {
			for (let i = item.children.length - 1; i >= 0; i--) {
				stack.unshift(item.children[i])
			}
		}
	}
	return result
}

export function getSubMeetingBySmcuMtid(tree: MccModel<Meeting>, id: string) {
	let stack: MccModel<IMcc>[] = [tree]
	let result: MccModel<IMcc>[] = []
	while (stack.length > 0) {
		const item = stack.shift()!
		if (!item.mcc.isMt && item.mcc.smcuMtid === id) {
			result = item.children.filter((x) => !x.mcc.isMt && x.mcc.status.isOnline)
			break
		}
		if (item.children && item.children.length > 0) {
			for (let i = item.children.length - 1; i >= 0; i--) {
				stack.unshift(item.children[i])
			}
		}
	}
	return result
}

export function mtsTranslator(mts: MccModel<IMcc>[]): MccCurrentMt[] {
	return mts.map((x) => {
		if (x.mcc.isMt) {
			if (x.mcc.isSimpleCascade) {
				return { account: x.mcc.e164, accountType: 10, moid: '', e164: x.mcc.e164 }
			} else {
				return { account: x.mcc.account, accountType: x.mcc.accountType, moid: x.mcc.moid, e164: x.mcc.e164 }
			}
		} else {
			return { account: x.mcc.account, accountType: 10, moid: '', e164: x.mcc.account }
		}
	})
}
